package com.kuang.gulimall.thirdtools.config;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;


import java.io.FileInputStream;
import java.io.FileNotFoundException;



public class cosConfig {

    private static final String secretId = "AKIDhsnaT9NSyFoVN1lhjallYDcEchWAqGis";
    private static final String secretKey = "DKJFv9CJAqJM9d7MThiVqwwoQwGNFm5D";
    private static final String regionName = "ap-nanjing";
    private static final String bucketName = "gulimall-hello-1305414787";
    private static final Integer length = 1000;


    public static COSClient getCosClient(){
        //1,初始化用户信息身份
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        Region region = new Region(regionName);
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }


    public String uploadFile(String filename,String keys){
        // Bucket的命名格式为 BucketName-APPID ，此处填写的存储桶名称必须为此格式
        try {
            FileInputStream fileInputStream = new FileInputStream(filename);
            // 设置 Content type, 默认是 application/octet-stream
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(length);
            COSClient cosClient = getCosClient();
            PutObjectResult putObjectResult = cosClient.putObject(new PutObjectRequest(bucketName, keys, fileInputStream, objectMetadata));
            String eTag = putObjectResult.getETag();
            cosClient.shutdown();
            System.out.println(eTag);
            System.out.println("成功");
            return "成功";
            // 关闭输入流...
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "失败";
        }
    }
}
